// https://leetcode.cn/problems/matrix-block-sum/description/

// 算法思路总结：
// 1. 二维前缀和快速计算矩阵区域和
// 2. 预处理构建前缀和矩阵dp
// 3. 利用前缀和公式计算K范围内块元素和
// 4. 处理边界情况确保索引有效
// 5. 时间复杂度：O(m×n)，空间复杂度：O(m×n)

#include <iostream>
using namespace std;

#include <vector>
#include <algorithm>

class Solution 
{
public:
    vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) 
    {
        int m = mat.size(), n = mat[0].size();
        vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));

        for (int i = 1 ; i <= m ; i++)
        {
            for (int j = 1 ; j <= n ; j++)
            {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + mat[i - 1][j - 1];
            }
        }

        vector<vector<int>> ret(m, vector<int>(n));
        for (int i = 1 ; i <= m ; i++)
        {
            for (int j = 1 ; j <= n ; j++)
            {
                int x1 = i - k, y1 = j - k, x2 = i + k, y2 = j + k;
                x1 = max(x1, 1);
                y1 = max(y1, 1);
                x2 = min(x2, m);
                y2 = min(y2, n);
                ret[i - 1][j - 1] = dp[x2][y2] - dp[x2][y1 - 1] - dp[x1 - 1][y2] + dp[x1 - 1][y1 - 1];
            }
        }
        
        return ret;
    }
};

int main()
{
    vector<vector<int>> mat1 = {{1,2,3},{4,5,6},{7,8,9}};
    vector<vector<int>> mat2 = {{1,2,3},{4,5,6},{7,8,9}};
    int k1 = 1, k2 = 2;

    Solution sol;

    auto vv1 = sol.matrixBlockSum(mat1, k1);
    auto vv2 = sol.matrixBlockSum(mat2, k2);

    for (const auto& v : vv1)
    {
        for (const int& num : v)
        {
            cout << num << " ";
        }
        cout << endl;
    }
    cout << endl;

    for (const auto& v : vv2)
    {
        for (const int& num : v)
        {
            cout << num << " ";
        }
        cout << endl;
    }
    cout << endl;

    return 0;
}